package com.dyson.concurrent.audition.demo05;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 卖票事例
 * 使用并发队列实现
 * 
 * 1064 毫秒
 */
public class SellTicketsTest04 {

	private static Queue<String> q = new ConcurrentLinkedQueue<>();
	

	public static void main(String[] args) throws InterruptedException {
		//初始化1千张票
		for(int i=0;i<1000;i++){
			q.add("Peter的"+(i+1)+"号票");
		}
		
		Thread[] threads=new Thread[10];
		long startTime=System.currentTimeMillis();
		//创建10条线程去做卖票工作
		for(int i=0;i<10;i++){
			Thread t = new Thread(){
				@Override
				public void run() {
					while(true){
						String ticket = q.poll();
						if(ticket==null){
							break;
						}
						System.out.println("卖掉了"+ticket);
					}
					System.out.println("票已经卖完……");
				}
			};
			threads[i]=t;
			t.start();
		}
		//等待所有线程执行结束
		for(Thread t:threads){
			t.join();
		}
		long endTime=System.currentTimeMillis();
		System.out.println("总共用时："+(endTime-startTime)+" 毫秒");
		
	}
}


